package com.xxl.job.executor.sample.frameless.test.wait_notifyDemo;

public class Difficult1 {

    static final Object room = new Object();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;

    //其它干活的线程，都要一直阻塞，效率太低
    //小南线程必须睡足 2s 后才能醒来，就算烟提前送到，也无法立刻醒来
    //加了 synchronized (room) 后，就好比小南在里面反锁了门睡觉，烟根本没法送进门，main 没加
    //synchronized 就好像 main 线程是翻窗户进来的
    //解决方法，使用 wait - notify 机制
    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (room) {
                System.out.println(Thread.currentThread().getName() + ":有烟没？" + hasCigarette);
                if (!hasCigarette) {
                    System.out.println(Thread.currentThread().getName() + ":没烟，先歇会儿！");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + ":有烟没？" + hasCigarette);
                if (hasCigarette) {
                    System.out.println(Thread.currentThread().getName() + ":可以开始干活了！");
                }
            }
        },"小王").start();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                synchronized (room) {
                    System.out.println(Thread.currentThread().getName() + ":可以开始干活了！");
                }
            },"其他人").start();
        }
        Thread.sleep(1000);
        new Thread(() -> {
//  获取到锁才能执行，sleep不会释放锁，得等小王线程释放锁才能执行该线程
//            synchronized (room) {
//                hasCigarette = true;
//                System.out.println(Thread.currentThread().getName() + ":烟到了！");
//            }
            hasCigarette = true;
            System.out.println(Thread.currentThread().getName() + ":烟到了！");
        },"送烟的").start();
    }
}
